/*********************************************************************
 * ThreadPool.java created on Feb 3, 2010
 *
 * This file is part of Sure Tech Support Portal System. 
 * Copyright @ 2010 Sure Tech (HK) Limited. All rights reserved.
 * Sure Tech PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *********************************************************************/
package com.bizdigger.thread.pool;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.pool.impl.GenericObjectPool;

/**
 * @Author: Mac Wang
 * @Date: Feb 3, 2010 3:04:35 PM 
 * @Email: mac@suretech.com.hk
 */

public class ThreadPool extends GenericObjectPool {
	private Log log = LogFactory.getLog(ThreadPool.class);
	
	public ThreadPool(ThreadObjectFactory factory)
	{
		super(factory);
		this.setMaxIdle(2);		// Maximum idle threads
		this.setMaxActive(4);	// Maximum active threads.
		this.setMinEvictableIdleTimeMillis(30000);	//Evictor runs every 30 secs.
		this.setTestOnBorrow(true);	// Check if the thread is still valid.
		this.setMaxWait(1000);	// Wait 1 second till a thread is available
	}
	
	public ThreadPool(ThreadObjectFactory factory, GenericObjectPool.Config config)
	{
		super(factory, config);
	}
	
	public Object borrowObjects() throws Exception
	{
		log.debug("borrow object...");
		
		return super.borrowObject();
	}
	
	public void returnObject(Object object) throws Exception
	{
		log.debug("return object:" + object);
		
		super.returnObject(object);
	}
	
	/**
	 * borrowObjects - Helper method, use this carefully since this could be
	 * a blocking call when the threads requested may not be avialable based
	 * on the configuration being used.
	 * @param num
	 * @return WorkerThread[]
	 */
	public synchronized WorkerThread[] borrowObjects(int num) {
		WorkerThread[] rtArr = new WorkerThread[num];
		for (int i = 0; i < num; i++) {
			WorkerThread rt; 
			try {
				rt = (WorkerThread) borrowObject();
	            rtArr[i] = rt;
			} catch (Exception e) {
				log.error(" borrowObjects failed.. ", e);
			}
		}
		return rtArr;
	}
}
